

function findNo(results, min = 5000, keyword) {
  const regex = /eplycomment-oml-2\">(\d{4,})<\/span>.*?No\.(\d+)/g;

  const maxNo = [0];
  for (const match of results.replace(/\s+/g, '').matchAll(regex)) {
    const num = parseInt(match[1]);
    const no = parseInt(match[2]);
    if (num > min) {
      maxNo.push(no);
      console.log(`数字 ${num} > 5000，对应的 No. 是 ${no}，歌手是 ${keyword}`);
    }
  }
  return Math.max(...maxNo);
}

function findMusic(keyword, timeout = 1) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const k = encodeURIComponent(keyword).replaceAll("%", "_");
       fetch(`https://www.hifini.com/search-${k}-1.htm`, {
        headers: {
          accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
          "accept-language": "zh-CN,zh;q=0.9",
          priority: "u=0, i",
          "sec-ch-ua":
            '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": '"macOS"',
          "sec-fetch-dest": "document",
          "sec-fetch-mode": "navigate",
          "sec-fetch-site": "same-origin",
          "sec-fetch-user": "?1",
          "upgrade-insecure-requests": "1",
        },
        referrer: `https://www.hifini.com/search-${k}-1.htm`,
        referrerPolicy: "strict-origin-when-cross-origin",
        body: null,
        method: "GET",
        mode: "cors",
        credentials: "include",
      })
        .then((e) => e.text())
        .then((e) => {
          resolve({
            keyword,
            number: findNo(e, 5000, keyword),
          })
        })
        .catch((e) => {
          reject({
            keyword,
            number: 0,
          });
        });
    }, 400 * timeout);
  });

}

function findGoodMusic(ks) {
  const p = ks.map((k, index) => findMusic(k, index + 1));
  Promise.allSettled(p).then((e) => {
    const last =  e.filter(t=>t.value.number).map(v=>v.value)
    console.log("🚀 ~ Promise.allSettled ~ last:", last)
    return last
  });
}

// 在这个域名里的控制台执行当前代码 https://www.hifini.com/search.htm
// todo 存放要查找的歌手
const keywords = window.peopleKeywords
// 查找歌手（歌手是 keywords 数组里的） 输出大于 5000 暂的歌曲
findGoodMusic(keywords);
